<template>
	<view class="container">
		<block v-if="(level1 || null) != null && (have_content || null) != null">
		  <!-- 分类选择页面 -->
		  <view v-if="currentStep === 'category'" class="category-selector">
		    <view class="sticky-header">
		      <view class="header-title">
		        <text class="title">选择商品分类</text>
		      </view>
		  
		      <view class="tab-header">
		        <view 
		          :class="['tab-item', activeLevel === 1 ? 'tab-active' : '']" 
		          @tap="handleBackToLevel1"
		        >
		          <text>{{ selectedLevel1 ? selectedLevel1.name : '一级分类' }}</text>
		        </view>
		  
		        <view 
		          v-if="selectedLevel1 && selectedLevel1.items && selectedLevel1.items.length > 0"
		          :class="['tab-item', activeLevel === 2 ? 'tab-active' : '']" 
		          @tap="handleBackToLevel2"
		        >
		          <text>{{ selectedLevel2 ? selectedLevel2.name : '二级分类' }}</text>
		        </view>
		  
		        <view 
		          v-if="selectedLevel2 && selectedLevel2.items && selectedLevel2.items.length > 0"
		          :class="['tab-item', activeLevel === 3 ? 'tab-active' : '']"
		        >
		          <text>{{ selectedLevel3 ? selectedLevel3.name : '三级分类' }}</text>
		        </view>
		      </view>
		    </view>
		  
		    <view class="category-list">
		      <!-- 一级分类列表 -->
		      <view v-if="activeLevel === 1">
		        <view 
		          v-for="(category, index) in level1" 
		          :key="category.id"
		          class="category-item"
		          @tap="handleLevel1Select(category)"
		        >
		          <text>{{ category.name }}</text>
		          <text v-if="category.items && category.items.length > 0" class="icon-right">></text>
		        </view>
		      </view>
		  
		      <!-- 二级分类列表 -->
		      <view v-if="activeLevel === 2">
		        <view 
		          v-for="(category, index) in level2" 
		          :key="category.id"
		          class="category-item"
		          @tap="handleLevel2Select(category)"
		        >
		          <text>{{ category.name }}</text>
		          <text v-if="category.items && category.items.length > 0" class="icon-right">></text>
		        </view>
		      </view>
		  
		      <!-- 三级分类列表 -->
		      <view v-if="activeLevel === 3">
		        <view 
		          v-for="(category, index) in level3" 
		          :key="category.id"
		          class="category-item"
		          @tap="handleLevel3Select(category)"
		        >
		          <text>{{ category.name }}</text>
		        </view>
		      </view>
		    </view>
		  </view>
		  
		  <!-- 商品详情页面 -->
		  <view v-else class="product-details">
		    <view class="sticky-header">
		      <view class="header-bar">
		        <view class="back-button" @tap="handleBackToList">
		          <text class="icon-back">←</text>
		        </view>
		        <text class="title">返回列表</text>
		        <view class="nav-buttons">
		          <button 
		            v-if="currentTabIndex > 0" 
		            class="prev-button" 
		            @tap="goToPrevStep"
		          >
		            上一步
		          </button>
		          <button class="next-button" @tap="goToNextStep">
		            <text class="progress-text">{{ currentTabIndex + 1 }}/{{ tabOrder.length }}</text>
		            <text>{{ isLastStep ? '提交' : '下一步' }}</text>
		          </button>
		        </view>
		      </view>
		    </view>
		  
		    <view class="content-container">
				<view v-if="is_open_system_category" class="category-info">
				  <view class="category-info-content">
					<text>已选分类: {{ selectedCategory.join(' > ') }}</text>
					<button class="edit-btn" @tap="handleBackToCategory">修改</button>
				  </view>
				</view>
		  
		      <!-- 基础信息 -->
		      <view v-if="activeTab === 'basic'" class="form-section">
		        <view class="section-header enhanced">
		          <text class="section-title">基础信息</text>
		        </view>
		  
		        <view class="form-item">
		          <view class="form-label">
		            <text>商品标题</text>
		            <text class="required">*</text>
		          </view>
		          <input type="text" v-model="basicInfo.title" placeholder="请输入商品标题" class="form-input" />
		        </view>
		  
		        <view class="form-item">
		          <view class="form-label">
		            <text>商品简述</text>
		          </view>
		          <textarea v-model="basicInfo.description" placeholder="请输入商品简述" class="form-textarea" />
		        </view>
		  
		        <view class="form-item">
		          <view class="form-label">
		            <text>商品型号</text>
		          </view>
		          <input type="text" v-model="basicInfo.model" placeholder="请输入商品型号" class="form-input" />
		        </view>
		  
		        <view class="form-item">
		          <view class="form-label">
		            <text>店铺商品分类</text>
		            <text class="required">*</text>
		          </view>
		          <picker 
		            :range="storeCategories" 
		            range-key="name" 
		            @change="onStoreCategoryChange"
		            class="form-picker"
		          >
		            <view class="picker-value">
		              <text>{{ basicInfo.storeCategory ? basicInfo.storeCategory : '请选择店铺商品分类' }}</text>
		            </view>
		          </picker>
		        </view>
		  
		        <view class="form-item">
		          <view class="form-label">
		            <text>品牌</text>
		          </view>
		          <picker 
		            :range="brands" 
		            range-key="name" 
		            @change="onBrandChange"
		            class="form-picker"
		          >
		            <view class="picker-value">
		              <text>{{ basicInfo.brand ? basicInfo.brand : '请选择品牌' }}</text>
		            </view>
		          </picker>
		        </view>
		  
		        <view class="form-item">
		          <view class="form-label">
		            <text>生产地</text>
		          </view>
		          <picker 
		            :range="locations" 
		            range-key="name" 
		            @change="onLocationChange"
		            class="form-picker"
		          >
		            <view class="picker-value">
		              <text>{{ basicInfo.location ? basicInfo.location : '请选择生产地' }}</text>
		            </view>
		          </picker>
		        </view>
		  
		        <view class="form-item">
		          <view class="form-label">
		            <text>库存单位</text>
		            <text class="required">*</text>
		          </view>
		          <input type="text" v-model="basicInfo.unit" placeholder="件/个/套" class="form-input" />
		        </view>
		  
		        <view class="form-item">
		          <view class="form-label">
		            <text>商品类型</text>
		          </view>
		          <picker 
		            :range="productTypes" 
		            range-key="name" 
		            @change="onProductTypeChange"
		            class="form-picker"
		          >
		            <view class="picker-value">
		              <text>{{ basicInfo.productType ? basicInfo.productType : '请选择商品类型' }}</text>
		            </view>
		          </picker>
		        </view>
		  
		        <view class="form-item">
		          <view class="form-label">
		            <text>商品封面</text>
		          </view>
		          <view class="upload-box" @tap="chooseImage('cover')">
		            <image v-if="basicInfo.coverImage" :src="basicInfo.coverImage" class="preview-image" mode="aspectFill"></image>
		            <view v-else class="upload-placeholder">
		              <text class="upload-icon">+</text>
		              <text class="upload-text">点击上传图片</text>
		            </view>
		          </view>
		        </view>
				
				<view v-if="is_can_add_price" class="form-item">
				  <view class="form-label">
				    <text>单规格库存</text>
				    <text class="required"></text>
				  </view>
				  <input type="number" v-model="basicInfo.stock" placeholder="填写后会自动加库存" class="form-input" />
				</view>
				
				<view v-if="is_goods_flag" class="form-item switch-item">
				  <text>是否现货</text>
				  <switch v-if="basicInfo.isnowgoods == 1" checked v-model="basicInfo.isnowgoods" color="#007aff" @change="onIsNowGoodsChange" />
				  <switch v-else v-model="basicInfo.isnowgoods" color="#007aff" @change="onIsNowGoodsChange" />
				</view>
				
		        <view class="form-item switch-item">
		          <text>是否扣减库存</text>
				  <switch v-if="basicInfo.reduceInventory == 1" checked v-model="basicInfo.reduceInventory" color="#007aff" @change="onReduceInventoryChange" />
				  <switch v-else v-model="basicInfo.reduceInventory" color="#007aff" @change="onReduceInventoryChange" />
		        </view>
		  
		        <view class="form-item switch-item">
		          <text>是否上架</text>
		          <switch v-if="basicInfo.isListed == 1" checked v-model="basicInfo.isListed" color="#007aff" @change="onIsListedChange" />
				  <switch v-else v-model="basicInfo.isListed" color="#007aff" @change="onIsListedChange" />
		        </view>
		      </view>
		  
		      <!-- 商品规格 -->
		      <view v-if="activeTab === 'specs'" class="form-section">
		        <view class="section-header enhanced">
		          <text class="section-title">商品规格</text>
		          <view class="switch-item">
		            <text>启用多规格</text>
					<!--<switch v-if="enableSpecs" checked v-model="enableSpecs" color="#007aff" @change="onenableSpecsChange" />
					<switch v-else v-model="enableSpecs" color="#007aff" @change="onenableSpecsChange" />-->
		          </view>
		        </view>
				<view v-if="!enableSpecs" class="specs-container">
					<text>您所在公司当前所属等级不允许添加价格，请直接下一步</text>
				</view>
		        <view v-if="enableSpecs" class="specs-container">
		          <view class="specs-section">
		            <text class="sub-title">规格项</text>
		            
		            <view v-for="(option, optionIndex) in specOptions" :key="option.id" class="spec-option">
		              <view class="spec-option-header">
		                <input 
		                  type="text" 
		                  v-model="option.name" 
		                  placeholder="规格名称，如颜色、尺寸" 
		                  class="form-input spec-name-input" 
		                />
		                <button class="delete-btn" @tap="removeSpecOption(option.id)">删除</button>
		              </view>
		              
		              <view class="spec-values">
		                <view 
		                  v-for="(value, valueIndex) in option.values" 
		                  :key="valueIndex" 
		                  class="spec-value-item"
		                >
		                  <input 
		                    type="text" 
		                    v-model="option.values[valueIndex]" 
		                    placeholder="规格值，如红色、蓝色" 
		                    class="form-input spec-value-input" 
		                  />
		                  <button class="delete-btn small" @tap="removeSpecValue(option.id, valueIndex)">×</button>
		                </view>
		                
		                <button class="add-btn" @tap="addSpecValue(option.id)">添加规格值</button>
		              </view>
		            </view>
		            <view class="spec-btn-box">
						<button class="add-btn" @tap="addSpecOption">添加规格项</button>
						<button class="primary-btn" @tap="updateSkuTable">生成规格表</button>
					</view>
		          </view>
		  
		          <view v-if="skuItems.length > 0" class="sku-table-section">
					<view class="section-header">
						<text class="sub-title">规格表</text>
						<view class="text-btn" @tap="toggleSkuTable">
							<view class="dis-inline">{{ showSkuTable ? '收起' : '展开' }}</view>
							<uni-icons class="spi" type="arrow-down" size="24" color="##007aff"></uni-icons>
						</view>
					</view>
		  
		            <view v-if="showSkuTable" class="sku-batch-actions">
		              <view class="batch-action">
		                <input type="number" placeholder="批量设置价格" class="form-input batch-input" v-model="batchPrice" />
		                <button class="text-btn" @tap="applyBatchPrice">应用</button>
		              </view>
		              <view class="batch-action">
		                <input type="number" placeholder="批量设置原价" class="form-input batch-input" v-model="batchOldPrice" />
		                <button class="text-btn" @tap="applyBatchOldPrice">应用</button>
		              </view>
		              <!--<view class="batch-action">
		                <input type="number" placeholder="批量设置库存" class="form-input batch-input" v-model="batchStock" />
		                <button class="text-btn" @tap="applyBatchStock">应用</button>
		              </view>-->
		            </view>
		  
		            <scroll-view v-if="showSkuTable" scroll-x class="sku-table-container">
		              <view class="sku-table">
		                <view class="sku-table-header">
		                  <view v-for="(option, index) in specOptions" :key="option.id" class="sku-table-cell">
		                    {{ option.name }}
		                  </view>
		                  <view class="sku-table-cell">价格</view>
						  <view class="sku-table-cell">原价</view>
		                  <!--<view class="sku-table-cell">库存</view>-->
		                  <view class="sku-table-cell">商品编码</view>
						  <view class="sku-table-cell sku-action-cell">操作</view>
		                </view>
		                
		                <view v-for="(item, index) in skuItems" :key="item.id" class="sku-table-row">
		                  <view v-for="(option, optIndex) in specOptions" :key="optIndex" class="sku-table-cell">
		                    {{ item.specs[option.name] }}
		                  </view>
		                  <view class="sku-table-cell">
		                    <input type="number" v-model="item.price" class="form-input sku-input" />
		                  </view>
						  <view class="sku-table-cell">
						    <input type="number" v-model="item.old_price" class="form-input sku-input" />
						  </view>
		                  <!--<view class="sku-table-cell">
		                    <input type="number" v-model="item.stock" class="form-input sku-input" />
		                  </view>-->
		                  <view class="sku-table-cell">
		                    <input type="text" v-model="item.code" class="form-input sku-input" />
		                  </view>
						  <view class="sku-table-cell sku-action-cell">
							<button class="delete-btn small" @tap="removeSkuItem(item.id)">删除</button>
						  </view>
		                </view>
		              </view>
		            </scroll-view>
		          </view>
		        </view>
		      </view>
		  
		      <!-- 商品参数 -->
		      <view v-if="activeTab === 'params'" class="form-section">
		        <view class="section-header enhanced">
		          <text class="section-title">商品参数</text>
		        </view>
		  
		        <view class="form-item">
		          <view class="form-label">
		            <text>参数模板</text>
		          </view>
		          <picker 
		            :range="parameterTemplates" 
		            range-key="name" 
		            @change="onTemplateChange"
		            class="form-picker"
		          >
		            <view class="picker-value">
		              <text>{{ selectedTemplateName || '请选择参数模板' }}</text>
		            </view>
		          </picker>
		        </view>
		  
		        <view v-if="parameters.length > 0" class="params-table">
		          <view class="params-table-header">
		            <view class="params-table-cell param-name">参数名</view>
		            <view class="params-table-cell param-value">参数值</view>
					<view class="params-table-cell param-action">操作</view>
		          </view>
		          
		          <view 
		            v-for="(param, index) in parameters" 
		            :key="param.id" 
		            class="params-table-row"
		          >
		            <view class="params-table-cell param-name">{{ param.name }}</view>
		            <view class="params-table-cell param-value">
		              <input type="text" v-model="param.value" placeholder="请输入参数值" class="form-input" />
		            </view>
					<view class="params-table-cell param-action">
						<button class="delete-btn small" @tap="removeParameter(param.id)">×</button>
					  </view>
		          </view>
		        </view>
		  
		        <view class="custom-params-section">
		          <view class="section-header">
		            <text class="sub-title">自定义参数</text>
		            <button class="add-btn" @tap="addCustomParameter">添加参数</button>
		          </view>
		  
		          <view v-if="customParameters.length > 0" class="params-table">
		            <view class="params-table-header">
		              <view class="params-table-cell param-name">参数名</view>
		              <view class="params-table-cell param-value">参数值</view>
		              <view class="params-table-cell param-action">操作</view>
		            </view>
		            
		            <view 
		              v-for="(param, index) in customParameters" 
		              :key="param.id" 
		              class="params-table-row"
		            >
		              <view class="params-table-cell param-name">
		                <input type="text" v-model="param.name" placeholder="参数名称" class="form-input" />
		              </view>
		              <view class="params-table-cell param-value">
		                <input type="text" v-model="param.value" placeholder="参数值" class="form-input" />
		              </view>
		              <view class="params-table-cell param-action">
		                <button class="delete-btn small" @tap="removeCustomParameter(param.id)">×</button>
		              </view>
		            </view>
		          </view>
		          
		          <view v-else class="empty-tip">
		            <text>暂无自定义参数，点击上方按钮添加</text>
		          </view>
		        </view>
		      </view>
		  
		      <!-- 商品相册 -->
		      <view v-if="activeTab === 'gallery'" class="form-section">
		        <view class="section-header enhanced">
		          <text class="section-title">商品相册</text>
		        </view>
		  
		        <view class="gallery-container">
		          <view class="gallery-grid">
		            <view 
		              v-for="(image, index) in galleryImages" 
		              :key="index" 
		              class="gallery-item"
		            >
		              <image :src="image" class="gallery-image" mode="aspectFill"></image>
		              <view class="delete-overlay" @tap="removeGalleryImage(index)">
		                <text class="delete-icon">×</text>
		              </view>
		            </view>
		            
		            <view class="gallery-item add-item" @tap="chooseImage('gallery')">
		              <text class="add-icon">+</text>
		              <text class="add-text">添加图片</text>
		            </view>
		          </view>
		          
		          <text class="gallery-tip">提示：若商品封面未传，则此处第一张图片将作为商品主图</text>
		        </view>
		      </view>
		  
		      <!-- 商品视频 -->
		      <view v-if="activeTab === 'video'" class="form-section">
		        <view class="section-header enhanced">
		          <text class="section-title">商品视频</text>
		        </view>
		  
		        <view class="video-container">
		          <view v-if="productVideo" class="video-preview">
		            <video :src="productVideo" class="video-player" controls></video>
		            <button class="delete-btn" @tap="removeVideo">删除视频</button>
		          </view>
		          
		          <view v-else class="upload-box" @tap="chooseVideo">
		            <view class="upload-placeholder">
		              <text class="upload-icon">+</text>
		              <text class="upload-text">点击上传视频</text>
		              <text class="upload-tip">支持mp4格式，大小不超过50MB</text>
		            </view>
		          </view>
		        </view>
		      </view>
		  
		      <!-- 电脑详情 -->
		      <view v-if="activeTab === 'desktop'" class="form-section">
		        <view class="section-header enhanced">
		          <text class="section-title">商品详情</text>
		        </view>
		        <view class="detail-editor">
		          <view class="editor-container sp-editor">
		            <sp-editor editorId="editor2" ref="editor2" @init="initEditor2" @input="rich_text_event2" @upinImage="up_in_image_event"></sp-editor>
		          </view>
		        </view>
		      </view>

			<!-- 虚拟信息 -->
			<view v-if="activeTab === 'virtual'" class="form-section">
			  <view class="section-header enhanced">
			    <text class="section-title">虚拟信息</text>
			  </view>
			
			  <view class="form-item">
			    <view class="editor-container sp-editor">
				  <sp-editor editorId="editor" ref="editor1" @init="initEditor" @input="rich_text_event" @upinImage="up_in_image_event"></sp-editor>
			    </view>
			    <text class="form-tip">请输入虚拟商品的使用说明、兑换方式等信息</text>
			  </view>
			</view>
		  
		      <!-- SEO信息 -->
		      <view v-if="activeTab === 'seo'" class="form-section">
		        <view class="section-header enhanced">
		          <text class="section-title">SEO信息</text>
		        </view>
		  
		        <view class="form-item">
		          <view class="form-label">
		            <text>SEO标题</text>
		          </view>
		          <input type="text" v-model="seoInfo.title" placeholder="SEO标题" class="form-input" />
		        </view>
		  
		        <view class="form-item">
		          <view class="form-label">
		            <text>SEO关键词</text>
		          </view>
		          <input type="text" v-model="seoInfo.keywords" placeholder="多个关键词用英文逗号分隔" class="form-input" />
		        </view>
		  
		        <view class="form-item">
		          <view class="form-label">
		            <text>SEO描述</text>
		          </view>
		          <textarea v-model="seoInfo.description" placeholder="SEO描述" class="form-textarea" />
		        </view>
		      </view>
			  
			  <component-popup :propShow="is_show_app_down_pross" propPosition="center">
			  	<view v-if="is_show_app_down_pross" class="show_app_down_pross">
			  		<view class="mask flex-center">
			  			<view class="content botton-radius">
			  				<view class="content-top">
			  					<text class="content-top-text">{{$t('fengcheche.progress')}}：{{app_down_pross}}%</text>
			  				</view>
			  			</view>
			  		</view>
			  	</view>
			  </component-popup>
		    </view>
		</view>
		<!-- #ifdef APP-PLUS -->
		<yk-authpup ref="authpup" type="top" @changeAuth="changeAuth" :permissionID="permissionID"></yk-authpup>
		<!-- #endif -->
		</block>
		<block v-else>
			<!-- 提示信息 -->
			<component-no-data :propStatus="data_list_loding_status" :propMsg="data_list_loding_msg"></component-no-data>
		</block>
	</view>
</template>

<script>
const app = getApp();
// #ifdef APP-PLUS
import ykAuthpup from "@/components/yk-authpup/yk-authpup";
// #endif
import componentNoData from '@/components/no-data/no-data';
import componentPopup from "@/components/popup/popup";
import componentBottomLine from '@/components/bottom-line/bottom-line';
import {classinfo_base_info, myRequest} from '@/pages/fcc/classinfo/public/common.js';
import spEditor from '../public/sp-editor/components/sp-editor/sp-editor.vue';

export default {
  data() {
    return {
		params: null,
		data_base: null,
		data_list_loding_status: 1,
		data_list_loding_msg: '',
		editor_path_type: '',
		permissionID: '',
		peraction:'',
		is_show_app_down_pross: false,
		app_down_pross: 0,
		is_can_add_price: false,
		is_goods_flag: false,
		is_open_system_category: false,
		have_content:false,
		editor1Instance: null, // 第一个编辑器实例
		editor2Instance: null,  // 第二个编辑器实例
      // 步骤控制
      currentStep: 'category',
      activeTab: 'basic',
      productId: '', // 保存商品ID，用于分步上传
      
      // 选项卡顺序，用于分步上传 , 'mobile'
      tabOrder: ['basic', 'specs', 'params', 'gallery', 'video', 'desktop', 'virtual', 'seo'],
      
      // 分类选择相关
      level1: [],
      level2: [],
      level3: [],
      selectedLevel1: null,
      selectedLevel2: null,
      selectedLevel3: null,
      activeLevel: 1,
      selectedCategory: [],
	  selectedCategoryId: 0,
      
      // 选项卡标签
      tabLabels: {
        basic: "基础信息",
        specs: "商品规格",
        params: "商品参数",
        gallery: "商品相册",
        video: "商品视频",
        //mobile: "手机详情",
        desktop: "详情",
		virtual: "虚拟信息",
        seo: "SEO信息",
      },
      
      // 基础信息
      basicInfo: {
        title: '',
        description: '',
        model: '',
        storeCategory: '',
		storeCategoryId: 0,
        brand: '',
		brandId: 0,
        location: '',
		locationId: 0,
        unit: '',
        productType: '',
		productValue: 0,
        coverImage: '',
        reduceInventory: 0,
        isListed: 0,
		stock: 0,
		isnowgoods: 0
      },
      
      // 下拉选项数据
      storeCategories: [],
      brands: [],
      locations: [],
      productTypes: [],
      
      // 商品规格相关
      enableSpecs: false,
      specOptions: [],
      skuItems: [],
      showSkuTable: true,
	  batchOldPrice: '',
      batchPrice: '',
      batchStock: '',
      
      // 商品参数相关
      parameterTemplates: [],
      selectedTemplateName: '',
      parameters: [],
      customParameters: [],
      
      // 商品相册
      galleryImages: [],
      
      // 商品视频
      productVideo: '',
      
      // 商品详情
      mobileDetails: [],
      desktopDetails: {
        content: ''
      },
      
      // 虚拟信息
      virtualInfo: {
        content: ''
      },
      
      // SEO信息
      seoInfo: {
        title: '',
        keywords: '',
        description: ''
      },
      
      // 上传状态
      uploadStatus: {
        basic: false,
        specs: false,
        params: false,
        gallery: false,
        video: false,
        mobile: false,
        desktop: false,
		virtual: false,
        seo: false
      },
    }
  },
  components: {
	  // #ifdef APP-PLUS
	  ykAuthpup,
	  // #endif
  	componentNoData,
	componentPopup,
  	componentBottomLine,
	spEditor
  },
  onLoad(params) {
      // 调用公共事件方法
      app.globalData.page_event_onload_handle(params);
	  
	  // 参数处理
	  params = app.globalData.launch_params_handle(params);
	  		
	  // 设置参数
	  this.setData({
	  	params: params,
	  });
	  
	  // 数据加载
	  this.init();
  },
  
  onShow() {
      // 调用公共事件方法
      app.globalData.page_event_onshow_handle();
  },
  computed: {
    // 当前选项卡在tabOrder中的索引
    currentTabIndex() {
      return this.tabOrder.indexOf(this.activeTab);
    },
    
    // 是否是最后一步
    isLastStep() {
      return this.currentTabIndex === this.tabOrder.length - 1;
    }
  },
  methods: {
	  init() {
	  	var self = this;
	  	classinfo_base_info()
	  	.then(data=>{
	  		this.setData({
	  			data_base: data
	  		});
	  		
	  		// 结束后调用数据
	  		self.get_data();
	  	});
	  },
	  
	  // 初始化数据
	  get_data() {
	  	uni.request({
	  		url: app.globalData.get_request_url("productinit", "shop", "classinfo"),
	  		method: 'POST',
	  		data: {
				id: this.params.id || 0
			},
	  		dataType: 'json',
	  		success: res => {console.log('--->初始化请求参数');console.log(res.data);
	  			uni.stopPullDownRefresh();
	  			if (res.data.code == 0) {
	  				var data = res.data.data;
	  				var upd_data = {
						level1: data.goods_category_list || null,
						goods_info: data.goods_info || null,
						data_list_loding_status: 3,
						storeCategories: data.shop_category || [],
						brands: data.brand_list || [],
						locations: data.region_province_list || [],
						productTypes: data.common_site_type_list || [],
						editor_path_type: data.editor_path_type || 'classinfo-product',
						productId: data.temp_id,
						goods_base_template: data.goods_base_template || null,
						is_can_add_price: data.is_can_add_price || false,
						is_goods_flag: data.is_goods_flag || false,
						is_open_system_category: data.is_open_system_category || false,
						have_content: true,
	  				};
					if(data.temp_cid > 0)
					{
						// 有已选系统分类时，跳过系统分类选择
						upd_data['selectedCategoryId'] = data.temp_cid;
						upd_data['selectedCategory'] = data.big_cid;
						upd_data['currentStep'] = 'details';
					}
					// 赋值初始化
					var need_load_base_spec = true;// 是否导入基础的规格模板
					if((data.goods_info || null) != null)
					{
						if((data.goods_info.content_basic || null) != null)
						{
							var temp_basicInfo = this.basicInfo;
							if((data.goods_info.content_basic.basicInfo || null) != null)
							{
								temp_basicInfo = data.goods_info.content_basic.basicInfo;
							}
							upd_data['basicInfo'] = temp_basicInfo;
						}
						
						// 已选参数模板，及当前设置的值
						if((data.goods_info.content_params || null) != null){
							upd_data['parameters'] = data.goods_info.content_params.parameters || [];
							upd_data['customParameters'] = data.goods_info.content_params.customParameters || [];
							upd_data['selectedTemplateName'] = data.goods_info.content_params.templateName || '';
						}
						
						// 已设置SKU信息
						if((data.goods_info.content_specs || null) != null){
							upd_data['enableSpecs'] = data.goods_info.content_specs.enableSpecs || this.enableSpecs;
							upd_data['specOptions'] = data.goods_info.content_specs.specOptions || [];
							upd_data['skuItems'] = data.goods_info.content_specs.skuItems || [];
							
							// 此时有真实已存的数据赋值，则不需要基础的规格赋值了
							need_load_base_spec = false;
						}
						
						// 已传商品相册
						if((data.goods_info.content_gallery || null) != null){
							upd_data['galleryImages'] = data.goods_info.content_gallery.galleryImages || [];
						}
						
						// 已传商品视频
						if((data.goods_info.content_video || null) != null){
							upd_data['productVideo'] = data.goods_info.content_video.productVideo || '';
						}
						
						// 已传商品手机详情
						if((data.goods_info.content_mobile || null) != null){
							upd_data['mobileDetails'] = data.goods_info.content_mobile.mobileDetails || '';
						}
						
						// 已传电脑手机详情
						if((data.goods_info.content_desktop || null) != null){
							var desktopDetails = {};
							desktopDetails['content'] = data.goods_info.content_desktop || '';
							upd_data['desktopDetails'] = desktopDetails;
						}
						
						// 已传虚拟信息
						if((data.goods_info.content_virtual || null) != null){
							var virtualInfo = {};
							virtualInfo['content'] = data.goods_info.content_virtual || '';
							upd_data['virtualInfo'] = virtualInfo;
						}
						
						// 已传SEO信息
						if((data.goods_info.content_seo || null) != null){
							upd_data['seoInfo'] = data.goods_info.content_seo.seoInfo || '';
						}
					}
					// 基础模板，只与已选系统分类对应
					if((data.goods_base_template || null) != null)
					{
						if((data.goods_base_template.params || null) != null)
						{
							upd_data['parameterTemplates'] = data.goods_base_template.params;
						}
						if((data.goods_base_template.spec || null) != null && need_load_base_spec)
						{
							upd_data['specOptions'] = data.goods_base_template.spec;
						}
					}
					
					// 是否允许添加价格
					if(data.is_can_add_price)
					{
						upd_data['enableSpecs'] = true;
					}
					
					this.setData(upd_data);
				} else {
					this.setData({
						data_list_loding_status: 0,
						data_list_loding_msg: res.data.msg
					});
					app.globalData.is_login_check(res.data, this, 'get_data');
				}
	  		},
	  		fail: () => {
	              uni.stopPullDownRefresh();
	              this.setData({
	                  data_list_loding_status: 2,
	                  data_list_loding_msg: this.$t('common.internet_error_tips'),
	              });
	  		}
	  	});
	  },
	  
    // 分类选择相关方法
    handleLevel1Select(category) {
      this.selectedLevel1 = category;
      this.selectedLevel2 = null;
      this.selectedLevel3 = null;
      
      if (category.items && category.items.length > 0) {
        this.level2 = category.items;
        this.activeLevel = 2;
      } else {
        // 如果只有一级分类，直接选择
        this.handleFinalSelection();
      }
    },
    
    handleLevel2Select(category) {
      this.selectedLevel2 = category;
      this.selectedLevel3 = null;
      
      if (category.items && category.items.length > 0) {
        this.level3 = category.items;
        this.activeLevel = 3;
      } else {
        // 如果只有两级分类，直接选择
        this.handleFinalSelection();
      }
    },
    
    handleLevel3Select(category) {
      this.selectedLevel3 = category;
      this.handleFinalSelection();
    },
    
    handleFinalSelection() {
      const categories = [];
	  let cid = 0;
      if (this.selectedLevel1) categories.push(this.selectedLevel1.name);
      if (this.selectedLevel2) categories.push(this.selectedLevel2.name);
      if (this.selectedLevel3) categories.push(this.selectedLevel3.name);
	  
	  if (this.selectedLevel1) cid = this.selectedLevel1.id;
	  if (this.selectedLevel2) cid = this.selectedLevel2.id;
	  if (this.selectedLevel3) cid = this.selectedLevel3.id;
      
	  this.selectedCategoryId = cid;
      this.selectedCategory = categories;
      this.currentStep = 'details';
      
      // 选择了最终分类后，获取对应的分类对应的基础模板
      this.createProductBase();
    },
    
    // 创建商品基础记录
    async createProductBase() {
      uni.showLoading({ title: '初始化商品...' });
      
      try {
        // 这里调用API创建商品基础记录
		const res = await myRequest(app.globalData.get_request_url("productbefore", "shop", "classinfo"), 'POST', {
			temp_id: this.productId,
			goods_cid : this.selectedCategoryId
		});
		 console.log('--->选在分类后初始化');
        console.log(res);
		uni.hideLoading();
        this.goods_base_template = res.data.goods_base_template || null;
		if((res.data.goods_base_template || null) != null)
		{
			if((res.data.goods_base_template.params || null) != null)
			{
				this.parameterTemplates = res.data.goods_base_template.params;
			}
			if((res.data.goods_base_template.spec || null) != null)
			{
				this.specOptions = res.data.goods_base_template.spec;
			}
		}
		
      } catch (error) {console.log(error);
        uni.hideLoading();
        uni.showToast({ title: '初始化商品失败', icon: 'none' });
      }
    },
    
    handleBackToLevel1() {
      this.activeLevel = 1;
    },
    
    handleBackToLevel2() {
      this.activeLevel = 2;
    },
    
    handleBackToCategory() {
      this.currentStep = 'category';
    },
    
    // 选项卡切换
    setActiveTab(tab) {
      this.activeTab = tab;
    },
	
	// 返回商品列表
	handleBackToList() {
	  app.globalData.page_back_prev_event();
	},
    
    // 上一步按钮
    goToPrevStep() {
      if (this.currentTabIndex > 0) {
        const prevIndex = this.currentTabIndex - 1;
        this.activeTab = this.tabOrder[prevIndex];
      }
    },
    
    // 基础信息相关方法
    onStoreCategoryChange(e) {
      const index = e.detail.value;
      this.basicInfo.storeCategory = this.storeCategories[index].name;
	  this.basicInfo.storeCategoryId = this.storeCategories[index].id;
    },
    
    onBrandChange(e) {
      const index = e.detail.value;
      this.basicInfo.brand = this.brands[index].name;
	  this.basicInfo.brandId = this.brands[index].id;
    },
    
    onLocationChange(e) {
      const index = e.detail.value;
      this.basicInfo.location = this.locations[index].name;
	  this.basicInfo.locationId = this.locations[index].id;
    },
    
    onProductTypeChange(e) {
      const index = e.detail.value;
      this.basicInfo.productType = this.productTypes[index].name;
	  this.basicInfo.productValue = this.productTypes[index].value;
    },
	
	// switch组件事件处理
	onReduceInventoryChange(e) {
	  this.basicInfo.reduceInventory = e.detail.value;
	},
	onIsNowGoodsChange(e) {
	  this.basicInfo.isnowgoods = e.detail.value;
	},
	onIsListedChange(e) {
	  this.basicInfo.isListed = e.detail.value;
	},
	// 多规格暂时不开启
	onenableSpecsChange(e) {
		app.globalData.showToast('暂未开放价格填写');
		return false;
		//this.enableSpecs = e.detail.value;
	},
	
	// 回调富文本内容
	rich_text_event(e) {
	    var new_data = this.virtualInfo;
	    new_data.content = e.html;
	    this.setData({
	        virtualInfo: new_data,
	    });
	},
	initEditor(editor) {
		console.log('----->initEditor---->');
		// 初始化编辑器内容
		editor.setContents({
		    html: (this.virtualInfo || null) !== null ? this.virtualInfo.content : '',
		});
	},
	
	// 回调富文本内容
	rich_text_event2(e) {
	    var new_data = this.desktopDetails;
	    new_data.content = e.html;
	    this.setData({
	        desktopDetails: new_data,
	    });
	},
	initEditor2(editor) {
		console.log('----->initEditor2---->');
		// 初始化编辑器内容
		editor.setContents({
		    html: (this.desktopDetails || null) !== null ? this.desktopDetails.content : '',
		});
	},
    
	// 文件上传
	chooseImage(type){
		if(app.globalData.is_android())
		{
			this.permissionID = 'CAMERA';
			setTimeout(()=>{
				this.$refs['authpup'].open(type);
			},500);
		}else{
			this.file_upload_event_true(type);
		}
	},
	// #ifdef APP-PLUS
	//用户授权权限后的回调
	changeAuth(e){
		if(this.permissionID == 'WRITE_EXTERNAL_STORAGE')
		{
			if(this.peraction == 'previewImage')
			{
				app.globalData.save_image_by_url(e);
			}else{
				this.file_upload_event_true(e);
			}
		}else{
			// 第一次是摄像头返回，再返回是相册权限，然后才继续执行
			this.peraction = 'fileupload';
			this.permissionID = 'WRITE_EXTERNAL_STORAGE';
			setTimeout(()=>{
				this.$refs['authpup'].open(e);
			},500);
		}
	}, 
	// #endif
	file_upload_event_true(type) {
	    uni.chooseImage({
	      count: type === 'gallery' ? 9 : 1,
	      success: (res) => {
	        if (type === 'cover') {
	          this.basicInfo.coverImage = res.tempFilePaths[0];
	        } else if (type === 'gallery') {
	          // 合并已有图片和新选择的图片
	          this.galleryImages = [...this.galleryImages, ...res.tempFilePaths];
	        }
	      }
	    });
	},
	
	// 上传图片
	up_in_image_event(tempFiles, editorCtx) {
	    var self = this;
	    // 使用 uniCloud.uploadFile 上传图片的示例方法（可适用多选上传）
	    tempFiles.forEach(async (item) => {
	        uni.showLoading({
	            title: self.$t('form.form.2e5rv3'),
	            mask: true,
	        });
	        await uni.uploadFile({
	            url: app.globalData.get_request_url('index', 'ueditor'),
	            // #ifdef APP-PLUS || H5
	            filePath: item.path,
	            // #endif
	            // #ifdef MP-WEIXIN
	            filePath: item.tempFilePath,
	            // #endif
	            name: 'upfile',
	            formData: {
	                action: 'uploadimage',
	                path_type: self.editor_path_type, // 路径类型，默认common
	            },
	            success: function (res) {
	                let data = JSON.parse(res.data);
	                if (res.statusCode == 200) {
	                    // 上传完成后处理
	                    editorCtx.insertImage({
	                        src: data.data.url, // 此处需要将图片地址切换成服务器返回的真实图片地址
	                        // width: '50%',
	                        alt: self.$t('form.form.3h58hv'),
	                        success: function (e) {},
	                    });
	                    uni.hideLoading();
	                }
	            },
	            fail: function (e) {
	                app.globalData.showToast(e.errMsg);
	                uni.hideLoading();
	            },
	        });
	    });
	},
    
    removeGalleryImage(index) {
      this.galleryImages.splice(index, 1);
    },
    
    // 视频选择
    chooseVideo() {
      uni.chooseVideo({
        maxDuration: 60,
        success: (res) => {
          this.productVideo = res.tempFilePath;
        }
      });
    },
    
    removeVideo() {
		if(this.productVideo.includes('classinfo'))
		{
			// 如果是远程的，则删除远程文件，需要先加个确认框
			uni.showModal({
			    title: this.$t('common.warm_tips'),
			    content: this.$t('fengcheche.classinfo.shanchuma'),
			    confirmText: this.$t('common.confirm'),
			    cancelText: this.$t('recommend-list.recommend-list.w9460o'),
			    success: (result) => {
			        if (result.confirm) {
			            uni.request({
			                url: app.globalData.get_request_url("deleteimg", "info", "classinfo"),
			                method: 'POST',
			                data: {
			                    value: this.productVideo,
			                },
			                dataType: 'json',
			                success: (res) => {
								console.log(res);
								this.productVideo = '';
			                },
			                fail: () => {
			                    
			                },
			            });
			        }
			    },
			});
		}else{
			this.productVideo = '';
		}
    },
    
    // 商品规格相关方法
    addSpecOption() {
      const newOption = {
        id: `spec-${Date.now()}`,
        name: "",
        values: [""]
      };
      this.specOptions.push(newOption);
    },
    
    removeSpecOption(id) {
      this.specOptions = this.specOptions.filter(option => option.id !== id);
    },
    
    addSpecValue(specId) {
      const index = this.specOptions.findIndex(option => option.id === specId);
      if (index !== -1) {
        this.specOptions[index].values.push("");
      }
    },
    
    removeSpecValue(specId, valueIndex) {
      const index = this.specOptions.findIndex(option => option.id === specId);
      if (index !== -1 && this.specOptions[index].values.length > 1) {
        this.specOptions[index].values.splice(valueIndex, 1);
      }
    },
	
    // 新增：删除单条SKU记录
	removeSkuItem(id) {
	  this.skuItems = this.skuItems.filter(item => item.id !== id);
	  app.globalData.showToast('删除成功');
	  // 如果删除后没有SKU了，隐藏表格
	  if (this.skuItems.length === 0) {
		this.showSkuTable = false;
	  }
	},
		
    updateSkuTable() {
      if (this.specOptions.length === 0) return;
      
      // 生成规格组合
      const generateCombinations = (options, current = {}, index = 0, result = []) => {
        if (index === options.length) {
          result.push({ ...current });
          return result;
        }
        
        const currentOption = options[index];
        for (const value of currentOption.values) {
          current[currentOption.name] = value;
          generateCombinations(options, current, index + 1, result);
        }
        
        return result;
      };
      
      const combinations = generateCombinations(this.specOptions);
      this.skuItems = combinations.map((combo, index) => ({
        id: `sku-${index}`,
        specs: combo,
        price: "",
		old_price: "",
        stock: "",
        code: ""
      }));
    },
    
    toggleSkuTable() {
      this.showSkuTable = !this.showSkuTable;
    },
    
    applyBatchPrice() {
      if (!this.batchPrice) return;
      
      this.skuItems.forEach(item => {
        item.price = this.batchPrice;
      });
    },
	
	applyBatchOldPrice() {
	  if (!this.batchOldPrice) return;
	  
	  this.skuItems.forEach(item => {
	    item.old_price = this.batchOldPrice;
	  });
	},
    
    applyBatchStock() {
      if (!this.batchStock) return;
      
      this.skuItems.forEach(item => {
        item.stock = this.batchStock;
      });
    },
    
    // 商品参数相关方法
    onTemplateChange(e) {
      const index = e.detail.value;
      const template = this.parameterTemplates[index];
      this.selectedTemplateName = template.name;
      
      // 深拷贝参数，避免修改原模板
      this.parameters = JSON.parse(JSON.stringify(template.config_data));
    },
    
    addCustomParameter() {
      const newParam = {
        id: `custom-${Date.now()}`,
        name: "",
        value: ""
      };
      this.customParameters.push(newParam);
    },
    
    removeCustomParameter(id) {
      this.customParameters = this.customParameters.filter(param => param.id !== id);
    },
	
	removeParameter(id) {
	  this.parameters = this.parameters.filter(param => param.id !== id);
	},
    
    // 分步上传相关方法
    
    // 前往下一步
    async goToNextStep() {
      if (!this.productId) {
        uni.showToast({ title: '请先选择商品分类', icon: 'none' });
        return;
      }
      
      if (this.isLastStep) {
        // 最后一步，提交商品
        await this.submitProduct();
      } else {
        // 保存当前步骤并前往下一步
        uni.showLoading({ title: '保存中...' });
        
        try {
          await this.saveStepData(this.activeTab);
          
          // 更新上传状态
          this.uploadStatus[this.activeTab] = true;
          
          // 前往下一步
          const nextIndex = this.currentTabIndex + 1;
          if (nextIndex < this.tabOrder.length) {
            this.activeTab = this.tabOrder[nextIndex];
          }
          
          uni.hideLoading();
        } catch (error) {
          uni.hideLoading();
          uni.showToast({ title: error.message, icon: 'none' });
        }
      }
    },
    
    // 保存步骤数据
    async saveStepData(step) {
      if (!this.productId) return Promise.reject(new Error('商品ID不存在'));
      
      // 根据步骤获取对应数据
      let data = {};
      let files = [];
      let error_msg = '';
	  
      switch (step) {
        case 'basic':
			// 处理封面图片，上传到远程服务器 若包含classinfo则说明是远程图片，无须再上传
			if (this.basicInfo.coverImage && !this.basicInfo.coverImage.includes('/upload/')) {
				const coverUrl = await this.uploadFile(this.basicInfo.coverImage);
				this.basicInfo.coverImage = coverUrl;
			}

			// 校验
			if(this.basicInfo.title == '')
			{
				return Promise.reject(new Error('商品标题必填'));
			}
			if(this.basicInfo.storeCategoryId == 0)
			{
				return Promise.reject(new Error('店铺分类必须选择'));
			}
			if(this.basicInfo.unit == 0)
			{
				return Promise.reject(new Error('库存单位必填'));
			}
          
          data = {
            productId: this.productId,
            basicInfo: this.basicInfo
          };
          break;
          
        case 'specs':
          data = {
            productId: this.productId,
            enableSpecs: this.enableSpecs,
            specOptions: this.specOptions,
            skuItems: this.skuItems
          };
          break;
          
        case 'params':
          data = {
            productId: this.productId,
            parameters: this.parameters,
            customParameters: this.customParameters,
            templateName: this.selectedTemplateName
          };
          break;
          
        case 'gallery':
          // 上传相册图片
          const galleryUrls = [];
          for (const image of this.galleryImages) {
			  console.log(image);
            if (!image.includes('/upload/')) {
              const imgUrl = await this.uploadFile(image);
              galleryUrls.push(imgUrl);
            } else {
              galleryUrls.push(image);
            }
          }
          this.galleryImages = galleryUrls;
		  
		  // 校验
          if(this.galleryImages.length == 0)
          {
          	return Promise.reject(new Error('商品相册必传'));
          }
		  
          data = {
            productId: this.productId,
            galleryImages: this.galleryImages
          };
          break;
          
        case 'video':
          // 上传视频
          if (this.productVideo && !this.productVideo.includes('/upload/')) {
            const videoUrl = await this.uploadFile(this.productVideo, 'uploadvideo');
            this.productVideo = videoUrl;
          }
          
          data = {
            productId: this.productId,
            productVideo: this.productVideo
          };
          break;
          
        case 'mobile':
          // 上传手机详情图片
          for (let i = 0; i < this.mobileDetails.length; i++) {
            if (this.mobileDetails[i].type === 'image' && 
                this.mobileDetails[i].content && !this.mobileDetails[i].content.includes('/upload/')) {
              const imgUrl = await this.uploadFile(this.mobileDetails[i].content);
              this.mobileDetails[i].content = imgUrl;
            }
          }
          
          data = {
            productId: this.productId,
            mobileDetails: this.mobileDetails
          };
          break;
          
        case 'desktop':
          // 上传电脑详情图片
          for (let i = 0; i < this.desktopDetails.length; i++) {
            if (this.desktopDetails[i].type === 'image' && 
                this.desktopDetails[i].content && !this.desktopDetails[i].content.includes('/upload/')) {
              const imgUrl = await this.uploadFile(this.desktopDetails[i].content);
              this.desktopDetails[i].content = imgUrl;
            }
          }
          
          data = {
            productId: this.productId,
            desktopDetails: this.desktopDetails
          };
          break;
		  
		case 'virtual':
		  data = {
			productId: this.productId,
			virtualInfo: this.virtualInfo
		  };
		  break;
          
        case 'seo':
          data = {
            productId: this.productId,
            seoInfo: this.seoInfo
          };
          break;
          
        default:
          return Promise.reject(new Error('未知步骤'));
      }
      
      // 调用API保存数据
      const res = await myRequest(app.globalData.get_request_url("productsave", "shop", "classinfo"), 'POST', {
		step: step,
		data: data,
		temp_id: this.productId
      });
    },
    
    // 提交商品
    async submitProduct() {
      uni.showLoading({ title: '提交中...' });
      
      try {
        // 保存最后一步
        await this.saveStepData(this.activeTab);
        
        // 更新上传状态
        this.uploadStatus[this.activeTab] = true;
        
        // 提交商品
		const res = await myRequest(app.globalData.get_request_url("productsubmit", "shop", "classinfo"), 'POST', {
			temp_id: this.productId
		});
        
        uni.hideLoading();
        uni.showToast({ title: '提交成功', icon: 'success' });
        
        // 跳转到商品列表页
        setTimeout(() => {
			app.globalData.page_back_prev_event();
        }, 1500);
      } catch (error) {
        uni.hideLoading();
        uni.showToast({ title: '提交失败: ' + error.message, icon: 'none' });
      }
    },
    
    // 文件上传工具方法
    uploadFile(filePath, action_type="uploadimage") {
		var self = this;
      return new Promise((resolve, reject) => {
        //uni.showLoading({ title: '上传中...' });
		self.setData({
			is_show_app_down_pross: true,
		});
        const uploadTask = uni.uploadFile({
            url: app.globalData.get_request_url('index', 'ueditor'),
            filePath: filePath,
            name: 'upfile',
            formData: {
                action: action_type,
                path_type: self.editor_path_type
            },
            success: function (res) {
        		var data = typeof res.data == 'object' ? res.data : JSON.parse(res.data);
                resolve(data.data.url);
            },
            fail: (err) => {
        		reject(err);
            }
        });
        
        uploadTask.onProgressUpdate((res) => {
           self.app_down_pross = res.progress;
		   if(res.progress == 100)
		   {
			   self.setData({
			   	is_show_app_down_pross: false,
			   });
		   }
        });
		
      });
    },

    // API请求工具方法
    apiRequest(url, data) {
      return new Promise((resolve, reject) => {
        uni.request({
          url: url,
          method: 'POST',
          data: data,
          success: (res) => {
            if (res.statusCode === 200 && res.data.success) {
              resolve(res.data);
            } else {
              reject(new Error(res.data.message || '请求失败'));
            }
          },
          fail: (err) => {
            reject(err);
          }
        });
      });
    }
  }
}
</script>

<style>
@import './product-saveinfo.css';
</style>